package com.apress.springrecipes.shop;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.Locale;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;

public class Cashier implements BeanNameAware, MessageSourceAware,
		ApplicationEventPublisherAware, StorageConfig { // implements
														// InitializingBean,
														// DisposableBean {
	private String name;
	private String path;
	private BufferedWriter writer;
	@SuppressWarnings("unused")
	private ApplicationEventPublisher applicationEventPublisher;
	private MessageSource messageSource;

	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}

	public void setBeanName(String beanName) {
		this.name = beanName;
	}

	// public void setName(String name) {
	// this.name = name;
	// }

	public void setPath(String path) {
		this.path = path;
	}

	@PostConstruct
	public void openFile() throws IOException {
		File logFile = new File(path, name + ".txt");
		writer = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(logFile, true)));
	}

	public void checkout(ShoppingCart cart) throws IOException {
		double total = 0;
		for (Product product : cart.getItems()) {
			total += product.getPrice();
		}
		writer.write(new Date() + "\t" + total + "\r\n");
		writer.flush();

		String alert = messageSource.getMessage("alert.checkout", new Object[] {
				total, new Date() }, Locale.US);
		System.out.println(alert);
	}

	@PreDestroy
	public void closeFile() throws IOException {
		writer.close();
	}

	@Override
	public String getPath() {
		// TODO Auto-generated method stub
		return path;
	}

	@Override
	public void setApplicationEventPublisher(
			ApplicationEventPublisher applicationEventPublisher) {
		// TODO Auto-generated method stub

	}

	// @Override
	// public void afterPropertiesSet() throws Exception {
	// // TODO Auto-generated method stub
	// openFile();
	//
	// }
	//
	// @Override
	// public void destroy() throws Exception {
	// // TODO Auto-generated method stub
	// closeFile();
	//
	// }
}
